<script setup>
import { ref, onMounted } from 'vue'

// 响应式数据
const files = ref([])
const previewFiles = ref([])
const customName = ref('')
const tags = ref('')
const description = ref('')
const fileList = ref([])
const isUploading = ref(false)
const uploadProgress = ref(0)
const message = ref('')
const messageType = ref('')

// 文件输入引用
const fileInput = ref(null)
const previewInput = ref(null)

// 服务器地址
const SERVER_URL = 'http://192.168.1.119:5000'

// 页面加载时获取文件列表
onMounted(() => {
    refreshFileList()
})

// 处理文件选择
const handleFileSelect = (event) => {
    files.value = Array.from(event.target.files)
}

// 处理预览图选择
const handlePreviewSelect = (event) => {
    previewFiles.value = Array.from(event.target.files)
}

// 上传文件
const uploadFiles = async () => {
    if (files.value.length === 0) {
        showMessage('请选择要上传的文件', 'error')
        return
    }

    isUploading.value = true
    uploadProgress.value = 0

    const formData = new FormData()
    
    // 添加文件
    files.value.forEach(file => {
        formData.append('files', file)
    })
    
    // 添加预览图
    previewFiles.value.forEach(preview => {
        formData.append('previews', preview)
    })
    
    // 添加元数据
    if (customName.value.trim()) {
        formData.append('custom_name', customName.value.trim())
    }
    if (tags.value.trim()) {
        formData.append('tags', tags.value.trim())
    }
    if (description.value.trim()) {
        formData.append('description', description.value.trim())
    }

    try {
        const xhr = new XMLHttpRequest()
        
        // 监听上传进度
        xhr.upload.addEventListener('progress', (e) => {
            if (e.lengthComputable) {
                uploadProgress.value = Math.round((e.loaded / e.total) * 100)
            }
        })

        // 处理响应
        xhr.addEventListener('load', () => {
            isUploading.value = false
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText)
                showMessage(response.message, 'success')
                clearForm()
                refreshFileList()
            } else {
                const response = JSON.parse(xhr.responseText)
                showMessage(response.error || '上传失败', 'error')
            }
        })

        xhr.addEventListener('error', () => {
            isUploading.value = false
            showMessage('网络错误，上传失败', 'error')
        })

        xhr.open('POST', `${SERVER_URL}/upload`)
        xhr.send(formData)
        
    } catch (error) {
        isUploading.value = false
        showMessage('上传失败: ' + error.message, 'error')
    }
}

// 清空表单
const clearForm = () => {
    files.value = []
    previewFiles.value = []
    customName.value = ''
    tags.value = ''
    description.value = ''
    if (fileInput.value) fileInput.value.value = ''
    if (previewInput.value) previewInput.value.value = ''
}

// 刷新文件列表
const refreshFileList = async () => {
    try {
        const response = await fetch(`${SERVER_URL}/files`)
        const data = await response.json()
        fileList.value = data.files || []
    } catch (error) {
        console.error('获取文件列表失败:', error)
        showMessage('获取文件列表失败', 'error')
    }
}

// 下载文件
const downloadFile = (fileId) => {
    window.open(`${SERVER_URL}/download/${encodeURIComponent(fileId)}`, '_blank')
}

// 删除文件
const deleteFile = async (fileId, fileName) => {
    if (!confirm(`确定要删除文件 "${fileName}" 吗？`)) {
        return
    }

    try {
        const response = await fetch(`${SERVER_URL}/delete/${encodeURIComponent(fileId)}`, {
            method: 'DELETE'
        })
        const data = await response.json()
        
        if (data.success) {
            showMessage(data.message, 'success')
            refreshFileList()
        } else {
            showMessage(data.error, 'error')
        }
    } catch (error) {
        showMessage('删除文件失败', 'error')
    }
}

// 显示消息
const showMessage = (text, type) => {
    message.value = text
    messageType.value = type
    setTimeout(() => {
        message.value = ''
        messageType.value = ''
    }, 5000)
}

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 触发文件选择
const triggerFileSelect = () => {
    fileInput.value?.click()
}

// 触发预览图选择
const triggerPreviewSelect = () => {
    previewInput.value?.click()
}
</script>

<template>
    <div class="container">
        <!-- 上传区域 -->
        <div class="upload-container">
            <!-- 左侧上传区域 -->
            <div class="upload-section">
                <h3>📤 文件上传</h3>
                
                <!-- 文件选择区域 -->
                <div class="upload-areas">
                    <div class="upload-area" @click="triggerPreviewSelect">
                        <div class="preview-img">
                            <span v-if="previewFiles.length === 0">📷 选择预览图</span>
                            <span v-else>✅ 已选择 {{ previewFiles.length }} 个预览图</span>
                        </div>
                    </div>
                    
                    <div class="upload-area" @click="triggerFileSelect">
                        <div class="assets">
                            <span v-if="files.length === 0">📁 选择文件</span>
                            <span v-else>✅ 已选择 {{ files.length }} 个文件</span>
                        </div>
                    </div>
                </div>

                <!-- 隐藏的文件输入 -->
                <input 
                    ref="fileInput"
                    type="file" 
                    multiple 
                    @change="handleFileSelect"
                    style="display: none"
                    accept="*/*"
                >
                <input 
                    ref="previewInput"
                    type="file" 
                    multiple 
                    @change="handlePreviewSelect"
                    style="display: none"
                    accept="image/*"
                >

                <!-- 上传进度 -->
                <div v-if="isUploading" class="progress-container">
                    <div class="progress-bar">
                        <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
                    </div>
                    <div class="progress-text">上传中... {{ uploadProgress }}%</div>
                </div>

                <!-- 消息显示 -->
                <div v-if="message" :class="['message', messageType]">
                    {{ message }}
                </div>
            </div>

            <!-- 右侧信息区域 -->
            <div class="info-container">
                <h3>📝 文件信息</h3>
                
                <div class="form-group">
                    <label>自定义文件名 (可选):</label>
                    <input 
                        v-model="customName" 
                        type="text" 
                        placeholder="留空使用原文件名"
                        class="form-input"
                    >
                </div>

                <div class="form-group">
                    <label>文件标签 (可选):</label>
                    <input 
                        v-model="tags" 
                        type="text" 
                        placeholder="用逗号分隔多个标签，如: 图片,设计,素材"
                        class="form-input"
                    >
                </div>

                <div class="form-group">
                    <label>文件描述 (可选):</label>
                    <textarea 
                        v-model="description" 
                        placeholder="文件描述信息"
                        class="form-textarea"
                        rows="4"
                    ></textarea>
                </div>

                <div class="action-buttons">
                    <button 
                        @click="uploadFiles" 
                        :disabled="isUploading || files.length === 0"
                        class="btn btn-primary"
                    >
                        {{ isUploading ? '上传中...' : '上传文件' }}
                    </button>
                    <button @click="clearForm" class="btn btn-secondary">清空</button>
                    <button @click="refreshFileList" class="btn btn-secondary">刷新列表</button>
                </div>
            </div>
        </div>

        <!-- 文件列表区域 -->
        <div class="file-list-container">
            <h3>📋 文件列表</h3>
            
            <div v-if="fileList.length === 0" class="empty-state">
                暂无文件
            </div>
            
            <div v-else class="file-list">
                <div v-for="file in fileList.slice(0, 1)" :key="file.id" class="file-item">
                    <div class="file-preview">
                        <img 
                            v-if="file.preview_url" 
                            :src="`${SERVER_URL}/preview/${file.preview_url}`" 
                            alt="预览"
                            class="preview-image"
                        >
                        <div v-else class="no-preview">📄</div>
                    </div>
                    
                    <div class="file-info">
                        <div class="file-name">{{ file.display_name || file.original_name }}</div>
                        <div class="file-meta">
                            大小: {{ formatFileSize(file.size) }} | 
                            修改时间: {{ file.modified }} | 
                            类型: {{ file.type }}
                        </div>
                        <div v-if="file.description" class="file-description">
                            {{ file.description }}
                        </div>
                        <div v-if="file.tags && file.tags.length > 0" class="file-tags">
                            <span v-for="tag in file.tags" :key="tag" class="tag">{{ tag }}</span>
                        </div>
                    </div>
                    
                    <div class="file-actions">
                        <button @click="downloadFile(file.id)" class="btn btn-small">下载</button>
                        <button @click="deleteFile(file.id, file.display_name)" class="btn btn-small btn-danger">删除</button>
                    </div>
                </div>
            </div>
        </div>
     </div>
 </template>

<style scoped>
.container {
    max-width: calc(100vw - 120px); /* 减掉侧边栏的距离 */
    margin: 0 auto;
    margin-left: 100px;
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 上传区域 */
.upload-container {
    display: flex;
    gap: 30px;
    margin-bottom: 40px;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.upload-section {
    flex: 1;
}

.upload-section h3 {
    margin: 0 0 20px 0;
    color: #333;
    font-size: 1.4em;
    font-weight: 600;
}

.upload-areas {
    display: flex;
    flex-direction: column; /* 改为上下布局 */
    gap: 20px;
    margin-bottom: 20px;
}

.upload-area {
    flex: 1;
    cursor: pointer;
    transition: transform 0.2s ease;
}

.upload-area:hover {
    transform: translateY(-2px);
}

.preview-img, .assets {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 40px 20px;
    border-radius: 12px;
    text-align: center;
    font-weight: 500;
    font-size: 1.1em;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.preview-img:hover, .assets:hover {
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    transform: translateY(-2px);
}

.assets {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    box-shadow: 0 4px 15px rgba(240, 147, 251, 0.3);
}

.assets:hover {
    box-shadow: 0 6px 20px rgba(240, 147, 251, 0.4);
}

/* 进度条 */
.progress-container {
    margin: 20px 0;
}

.progress-bar {
    width: 100%;
    height: 8px;
    background: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #667eea, #764ba2);
    transition: width 0.3s ease;
}

.progress-text {
    text-align: center;
    margin-top: 10px;
    font-weight: 500;
    color: #667eea;
}

/* 消息显示 */
.message {
    padding: 12px 16px;
    border-radius: 8px;
    margin: 15px 0;
    font-weight: 500;
}

.message.success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.message.error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

/* 信息区域 */
.info-container {
    flex: 1;
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.info-container h3 {
    margin: 0 0 25px 0;
    color: #333;
    font-size: 1.4em;
    font-weight: 600;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #555;
}

.form-input, .form-textarea {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.3s ease;
    box-sizing: border-box;
}

.form-input:focus, .form-textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
    resize: vertical;
    min-height: 100px;
    font-family: inherit;
}

/* 按钮 */
.action-buttons {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-block;
    text-align: center;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover:not(:disabled) {
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    transform: translateY(-2px);
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
    transform: translateY(-1px);
}

.btn-small {
    padding: 8px 16px;
    font-size: 12px;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

/* 文件列表区域 */
.file-list-container {
    background: white;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.file-list-container h3 {
    margin: 0 0 25px 0;
    color: #333;
    font-size: 1.4em;
    font-weight: 600;
}

.empty-state {
    text-align: center;
    color: #6c757d;
    font-style: italic;
    padding: 40px;
    background: #f8f9fa;
    border-radius: 8px;
}

.file-list {
    display: grid;
    gap: 20px;
}

.file-item {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 12px;
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.file-item:hover {
    background: #e9ecef;
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.file-preview {
    flex-shrink: 0;
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    background: #dee2e6;
    display: flex;
    align-items: center;
    justify-content: center;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.no-preview {
    font-size: 2em;
    color: #6c757d;
}

.file-info {
    flex: 1;
    min-width: 0;
}

.file-name {
    font-weight: 600;
    font-size: 1.1em;
    color: #333;
    margin-bottom: 8px;
    word-break: break-word;
}

.file-meta {
    color: #6c757d;
    font-size: 0.9em;
    margin-bottom: 8px;
}

.file-description {
    color: #495057;
    font-size: 0.95em;
    margin-bottom: 10px;
    line-height: 1.4;
}

.file-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.tag {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8em;
    font-weight: 500;
}

.file-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .upload-container {
        flex-direction: column;
        gap: 20px;
        padding: 20px;
    }
    
    .upload-areas {
        flex-direction: column;
    }
    
    .file-item {
        flex-direction: column;
        text-align: center;
        gap: 15px;
    }
    
    .file-actions {
        justify-content: center;
    }
    
    .action-buttons {
        justify-content: center;
    }
}

@media (max-width: 480px) {
    .container {
        padding: 10px;
    }
    
    .upload-container,
    .file-list-container {
        padding: 15px;
    }
    
    .info-container {
        padding: 20px;
    }
}
</style>